import type { User, UserManagementAction, UserOperationLog } from '@/types'
import { mockUsers, mockUserOperationLogs } from './mock'
import { LocalStorage } from '@/utils/storage'

/**
 * 用户管理API
 */
export class UserManagementAPI {
  /**
   * 获取所有用户
   */
  static getAllUsers(): User[] {
    return LocalStorage.getUsers()
  }

  /**
   * 根据ID获取用户
   */
  static getUserById(id: string): User | undefined {
    const users = LocalStorage.getUsers()
    return users.find((user) => user.id === id)
  }

  /**
   * 更新用户信息
   */
  static updateUser(userId: string, updates: Partial<User>): boolean {
    try {
      const users = LocalStorage.getUsers()
      const userIndex = users.findIndex((user) => user.id === userId)

      if (userIndex === -1) {
        throw new Error('用户不存在')
      }

      // 更新用户信息
      users[userIndex] = {
        ...users[userIndex],
        ...updates,
        updatedAt: new Date().toISOString(),
      }

      // 保存到本地存储
      localStorage.setItem('novel_app_users', JSON.stringify(users))

      return true
    } catch (error) {
      console.error('更新用户失败:', error)
      return false
    }
  }

  /**
   * 执行用户管理操作
   */
  static executeUserAction(
    userId: string,
    action: UserManagementAction,
    operatorId: string,
    operatorName: string,
  ): boolean {
    try {
      const user = this.getUserById(userId)
      if (!user) {
        throw new Error('用户不存在')
      }

      const oldValue: any = {}
      const newValue: any = {}
      let description = ''

      switch (action.type) {
        case 'ban':
          oldValue.status = user.status
          newValue.status = 'banned'
          newValue.banReason = action.reason || '违规行为'
          if (action.duration) {
            const banExpireDate = new Date()
            banExpireDate.setDate(banExpireDate.getDate() + action.duration)
            newValue.banExpireDate = banExpireDate.toISOString()
          }
          description = `封号${action.duration ? action.duration + '天' : '永久'}: ${action.reason}`
          break

        case 'unban':
          oldValue.status = user.status
          oldValue.banReason = user.banReason
          oldValue.banExpireDate = user.banExpireDate
          newValue.status = 'active'
          newValue.banReason = undefined
          newValue.banExpireDate = undefined
          description = '解除封号'
          break

        case 'suspend':
          oldValue.status = user.status
          newValue.status = 'suspended'
          if (action.duration) {
            const suspendExpireDate = new Date()
            suspendExpireDate.setDate(suspendExpireDate.getDate() + action.duration)
            newValue.banExpireDate = suspendExpireDate.toISOString()
          }
          description = `暂停账号${action.duration ? action.duration + '天' : ''}: ${action.reason}`
          break

        case 'activate':
          oldValue.status = user.status
          newValue.status = 'active'
          newValue.banReason = undefined
          newValue.banExpireDate = undefined
          description = '激活账号'
          break

        case 'recharge':
          oldValue.balance = user.balance
          newValue.balance = user.balance + (action.amount || 0)
          newValue.totalRecharge = user.totalRecharge + (action.amount || 0)
          description = `充值 ${action.amount} 书币: ${action.reason}`
          break

        case 'deduct':
          oldValue.balance = user.balance
          newValue.balance = Math.max(0, user.balance - (action.amount || 0))
          newValue.totalConsumption = user.totalConsumption + (action.amount || 0)
          description = `扣除 ${action.amount} 书币: ${action.reason}`
          break

        case 'grant_vip':
          oldValue.vipStatus = user.vipStatus
          oldValue.vipExpireDate = user.vipExpireDate
          newValue.vipStatus = action.vipType || 'monthly'

          const vipExpireDate = new Date()
          if (action.vipType === 'yearly') {
            vipExpireDate.setFullYear(vipExpireDate.getFullYear() + 1)
          } else {
            vipExpireDate.setMonth(vipExpireDate.getMonth() + 1)
          }
          newValue.vipExpireDate = vipExpireDate.toISOString()
          description = `赠送${action.vipType === 'yearly' ? '年度' : '月度'}VIP: ${action.reason}`
          break

        case 'revoke_vip':
          oldValue.vipStatus = user.vipStatus
          oldValue.vipExpireDate = user.vipExpireDate
          newValue.vipStatus = 'none'
          newValue.vipExpireDate = undefined
          description = `取消VIP: ${action.reason}`
          break

        case 'change_level':
          oldValue.level = user.level
          newValue.level = action.newLevel || 1
          description = `等级调整: ${user.level} → ${action.newLevel}: ${action.reason}`
          break

        case 'reset_password':
          description = `重置密码: ${action.reason}`
          break

        default:
          throw new Error('未知操作类型')
      }

      // 更新用户信息
      const updateSuccess = this.updateUser(userId, newValue)
      if (!updateSuccess) {
        throw new Error('更新用户信息失败')
      }

      // 记录操作日志
      this.addOperationLog({
        id: Date.now().toString(),
        userId,
        operatorId,
        operatorName,
        type: action.type,
        description,
        oldValue,
        newValue,
        createdAt: new Date().toISOString(),
      })

      return true
    } catch (error) {
      console.error('执行用户操作失败:', error)
      return false
    }
  }

  /**
   * 添加操作日志
   */
  static addOperationLog(log: UserOperationLog): void {
    try {
      const logs = this.getOperationLogs()
      logs.unshift(log) // 添加到开头

      // 只保留最近1000条记录
      if (logs.length > 1000) {
        logs.splice(1000)
      }

      localStorage.setItem('novel_app_operation_logs', JSON.stringify(logs))
    } catch (error) {
      console.error('保存操作日志失败:', error)
    }
  }

  /**
   * 获取操作日志
   */
  static getOperationLogs(): UserOperationLog[] {
    try {
      const stored = localStorage.getItem('novel_app_operation_logs')
      if (stored) {
        return JSON.parse(stored)
      }

      // 如果没有存储的日志，返回默认日志
      localStorage.setItem('novel_app_operation_logs', JSON.stringify(mockUserOperationLogs))
      return mockUserOperationLogs
    } catch (error) {
      console.error('获取操作日志失败:', error)
      return []
    }
  }

  /**
   * 获取用户操作日志
   */
  static getUserOperationLogs(userId: string): UserOperationLog[] {
    const logs = this.getOperationLogs()
    return logs.filter((log) => log.userId === userId)
  }

  /**
   * 搜索用户
   */
  static searchUsers(keyword: string): User[] {
    const users = this.getAllUsers()
    if (!keyword.trim()) {
      return users
    }

    const searchKey = keyword.toLowerCase()
    return users.filter(
      (user) =>
        user.email.toLowerCase().includes(searchKey) ||
        user.nickname.toLowerCase().includes(searchKey) ||
        user.id.includes(searchKey),
    )
  }

  /**
   * 获取用户统计信息
   */
  static getUserStats() {
    const users = this.getAllUsers()

    return {
      total: users.length,
      active: users.filter((u) => u.status === 'active').length,
      banned: users.filter((u) => u.status === 'banned').length,
      suspended: users.filter((u) => u.status === 'suspended').length,
      vipUsers: users.filter((u) => u.vipStatus !== 'none').length,
      monthlyVip: users.filter((u) => u.vipStatus === 'monthly').length,
      yearlyVip: users.filter((u) => u.vipStatus === 'yearly').length,
      totalBalance: users.reduce((sum, u) => sum + u.balance, 0),
      totalRecharge: users.reduce((sum, u) => sum + u.totalRecharge, 0),
      totalConsumption: users.reduce((sum, u) => sum + u.totalConsumption, 0),
      adminCount: users.filter((u) => u.role === 'admin').length,
      moderatorCount: users.filter((u) => u.role === 'moderator').length,
    }
  }

  /**
   * 批量操作用户
   */
  static batchOperation(
    userIds: string[],
    action: UserManagementAction,
    operatorId: string,
    operatorName: string,
  ): { success: number; failed: number; errors: string[] } {
    let success = 0
    let failed = 0
    const errors: string[] = []

    for (const userId of userIds) {
      try {
        const result = this.executeUserAction(userId, action, operatorId, operatorName)
        if (result) {
          success++
        } else {
          failed++
          errors.push(`用户 ${userId} 操作失败`)
        }
      } catch (error) {
        failed++
        errors.push(`用户 ${userId}: ${(error as Error).message}`)
      }
    }

    return { success, failed, errors }
  }

  /**
   * 重置所有用户数据
   */
  static resetAllUsers(): boolean {
    try {
      localStorage.setItem('novel_app_users', JSON.stringify(mockUsers))
      localStorage.setItem('novel_app_operation_logs', JSON.stringify(mockUserOperationLogs))
      return true
    } catch (error) {
      console.error('重置用户数据失败:', error)
      return false
    }
  }

  /**
   * 导出用户数据
   */
  static exportUsers(): string {
    const users = this.getAllUsers()
    const logs = this.getOperationLogs()

    const exportData = {
      users,
      operationLogs: logs,
      exportTime: new Date().toISOString(),
      version: '1.0',
    }

    return JSON.stringify(exportData, null, 2)
  }

  /**
   * 导入用户数据
   */
  static importUsers(jsonData: string): boolean {
    try {
      const data = JSON.parse(jsonData)

      if (!data.users || !Array.isArray(data.users)) {
        throw new Error('无效的数据格式')
      }

      // 验证用户数据结构
      for (const user of data.users) {
        if (!user.id || !user.email || !user.nickname) {
          throw new Error('用户数据不完整')
        }
      }

      localStorage.setItem('novel_app_users', JSON.stringify(data.users))

      if (data.operationLogs && Array.isArray(data.operationLogs)) {
        localStorage.setItem('novel_app_operation_logs', JSON.stringify(data.operationLogs))
      }

      return true
    } catch (error) {
      console.error('导入用户数据失败:', error)
      return false
    }
  }
}
